/**
 * @file dbtypeedition.c
 * @brief Fichier source du module dbtypeedition.
 *
 * @author Rachid Delory, Mamadou Keita, Florian Bernard
 */

/* *********************************************************************

                       Librairies de database

********************************************************************* */

#include "dbtypeedition.h"

/* *********************************************************************

                        Fonctions

********************************************************************* */
void recuperation_DTyp(TypeEdition **typeedition, const int id)
{
  if((*typeedition) && id > 0)
    {
      DataBase data;
      ouvrir_Db();
      /* Récupération de ceux qui ont comme père id */
      prepare_Db(&data, "select rowid, libelle from typeedition where rowid = ?");
      bindValueInt_Db(&data, 1, id);

      while(execute_Db(&data))
	{
	  if((*typeedition) == NULL)
	    (*typeedition) = creer_Typ();
	  setId_Typ((*typeedition), getValueInt_Db(&data, 0));
	  setLibelle_Typ((*typeedition), getValueText_Db(&data, 1));
	}
      finalise_Db(&data);
    }
}

void insertion_DTyp(TypeEdition *typeedition)
{
  if(typeedition)
    {
      DataBase data;
      ouvrir_Db();
      if(getSup_Typ(typeedition) == 1)
	{
	  suppression_DTyp(getId_Typ(typeedition));
	  return;
	}
      if(getId_Typ(typeedition) == 0)
	{
	  prepare_Db(&data, "insert into typeedition (libelle) values (?)");
	}
      else
	{
	  if(getMaj_Typ(typeedition) == 1)
	    {
	      prepare_Db(&data, "update typeedition set libelle = ? where rowid = ?");
	      bindValueInt_Db(&data, 2, getId_Typ(typeedition));
	    }
	  else
	    return;
	}

      bindValueText_Db(&data, 1, getLibelle_Typ(typeedition));
      if(execute_Db(&data))
	{

	}
      finalise_Db(&data);

      if(getId_Typ(typeedition) == 0)
	{
	  prepare_Db(&data, "select max(rowid) from typeedition");
	  if(execute_Db(&data))
	    {
	      setId_Typ(typeedition, getValueInt_Db(&data, 0));
	    }
	  finalise_Db(&data);
	}
    }
}

void suppression_DTyp(const int id)
{
  if (id > 0)
    {
      DataBase data;
      ouvrir_Db();
      prepare_Db(&data, "delete from TypeEdition where rowid = ?");
      bindValueInt_Db(&data, 1, id);
      if (execute_Db(&data))
        {

        }
      finalise_Db(&data);
      prepare_Db(&data, "update Livre set id_TypeEdition = 0 where id_TypeEdition = ?");
      bindValueInt_Db(&data, 1, id);
      if (execute_Db(&data))
        {

        }
      finalise_Db(&data);
    }
}
